#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
# This source file is part of the Cangjie project, licensed under Apache-2.0
# with Runtime Library Exception.
# 
# See https://cangjie-lang.cn/pages/LICENSE for license information.

import os
import glob
import sys
import platform
from optparse import OptionParser
from sys import _getframe as getframe

NORMAL_FONT = "\33[0m"  # 关闭所有属性
REVERSE_FONT = "\33[7m"  # 反显

def error(out_str, exit_flag=True):
    caller_frame = getframe().f_back
    call_file = os.path.basename(caller_frame.f_code.co_filename)
    call_line = caller_frame.f_lineno
    sys.stderr.write(REVERSE_FONT)
    sys.stderr.write("[Error]: <{}:{}> {}".format(call_file, call_line, out_str))
    sys.stderr.write(NORMAL_FONT)
    sys.stderr.write("\n")
    sys.stderr.flush()

    if exit_flag:
        sys.exit(1)

def modify_dest_html(basedir, destdir):
    for base_fpath in glob.glob(os.path.join(basedir, "*.html")):
        fname = os.path.basename(base_fpath)
        dest_fpath = os.path.join(destdir, fname)
        if not os.path.exists(dest_fpath):
            error("{} does not exist.".format(dest_fpath))

        with open(base_fpath, "r+", encoding="utf-8") as rfd:
            base_lines = rfd.readlines()
            base_lines = base_lines[8:]

        with open(dest_fpath, "r+", encoding="utf-8") as rfd:
            dest_lines = rfd.readlines()

        ignore_next = False
        for idx in range(len(base_lines)):
            # Ignore timestamp
            if base_lines[idx].strip() == r'<td class="headerName">Date:</td>':
                ignore_next = True
                continue

            # If flag ignore_next is True, do not need to compare.
            if ignore_next:
                ignore_next = False
                continue

            # Ignore cjcov version
            if base_lines[idx].find(r'Generated by: cjcov') != -1:
                continue

            # support windows
            if platform.system().lower() == "windows" and \
                    (base_lines[idx].find(r'class="coverFile"') != -1 or
                     base_lines[idx].find(r'class="headerValue"') != -1):
                base_lines[idx] = base_lines[idx].replace(r"</", r"`%tmp_tag`")
                base_lines[idx] = base_lines[idx].replace(r"/", "\\")
                base_lines[idx] = base_lines[idx].replace(r"`%tmp_tag`", r"</")

            if base_lines[idx] != dest_lines[idx]:
                error("base: '{}', result: '{}' are not same at line: {}.".format(base_fpath,dest_fpath, idx + 1))

def parse_arguments(argv=None):
    usage_str = r'Usage: python3 compare_html.py -b [basedir] -d [destdir]'

    parser = OptionParser(usage=usage_str)

    parser.add_option("-b", "--base", action="store",
                      dest="basedir",
                      default="",
                      help="the file path for cmetrics.xml path")

    parser.add_option("-d", "--dest", action="store",
                      dest="destdir",
                      default="",
                      help="the options for jekins")

    (options, args) = parser.parse_args(argv[1:])
    if len(args) != 0:
        print(usage_str)
        return

    if not os.path.exists(options.basedir):
        error("{} does not exists".format(options.basedir))

    if not os.path.exists(options.destdir):
        error("{} does not exists".format(options.destdir))

    return options.basedir, options.destdir


def main(argv=None):
    basedir, destdir = parse_arguments(sys.argv)
    modify_dest_html(basedir, destdir)

if __name__ == "__main__":
    main()


